/**
 * H5+ App后台运行支持
 * 确保在App后台运行时计时器也能正常工作
 */

// 检测是否为H5+ App环境
export const isH5PlusApp = () => {
  return typeof window.plus !== 'undefined' || 
         window.navigator.userAgent.includes('HBuilder') ||
         window.navigator.userAgent.includes('uni-app') ||
         window.navigator.userAgent.includes('DCloud')
}

// H5+ App后台运行管理器
class H5PlusBackgroundManager {
  constructor() {
    this.isInitialized = false
    this.backgroundTaskId = null
    this.keepAliveInterval = null
    this.visibilityChangeHandler = null
    
    if (isH5PlusApp()) {
      this.init()
    }
  }

  // 初始化后台运行支持
  init() {
    if (this.isInitialized) return
    
    try {
      // 设置页面可见性监听
      this.setupVisibilityHandling()
      
      // 设置后台运行保持
      this.setupBackgroundKeepAlive()
      
      // 设置网络状态监听
      this.setupNetworkMonitoring()
      
      this.isInitialized = true
      console.log('H5PlusBackgroundManager: 初始化成功')
    } catch (error) {
      console.error('H5PlusBackgroundManager: 初始化失败:', error)
    }
  }

  // 设置页面可见性处理
  setupVisibilityHandling() {
    if ('hidden' in document) {
      this.visibilityChangeHandler = () => {
        const isVisible = !document.hidden
        console.log(`H5PlusBackgroundManager: 页面可见性变化: ${isVisible ? '可见' : '隐藏'}`)
        
        if (isVisible) {
          this.onPageVisible()
        } else {
          this.onPageHidden()
        }
      }
      
      document.addEventListener('visibilitychange', this.visibilityChangeHandler)
    }
  }

  // 设置后台运行保持
  setupBackgroundKeepAlive() {
    if (typeof window.plus !== 'undefined' && window.plus.runtime) {
      try {
        // 请求后台运行权限
        this.requestBackgroundPermission()
        
        // 设置定期心跳，保持后台运行
        this.keepAliveInterval = setInterval(() => {
          this.sendKeepAliveSignal()
        }, 30000) // 30秒发送一次心跳
        
        console.log('H5PlusBackgroundManager: 后台运行保持已设置')
      } catch (error) {
        console.warn('H5PlusBackgroundManager: 后台运行权限请求失败:', error)
      }
    }
  }

  // 设置网络状态监听
  setupNetworkMonitoring() {
    if (typeof window.plus !== 'undefined' && window.plus.networkinfo) {
      try {
        window.plus.networkinfo.getCurrentType((type) => {
          console.log('H5PlusBackgroundManager: 当前网络类型:', type)
        })
        
        // 监听网络状态变化
        window.plus.networkinfo.addEventListener('change', (event) => {
          console.log('H5PlusBackgroundManager: 网络状态变化:', event)
        })
      } catch (error) {
        console.warn('H5PlusBackgroundManager: 网络状态监听设置失败:', error)
      }
    }
  }

  // 请求后台运行权限
  requestBackgroundPermission() {
    if (typeof window.plus !== 'undefined' && window.plus.runtime) {
      try {
        // 设置应用图标角标（保持活跃状态）
        if (window.plus.push) {
          window.plus.push.setAutoNotification(false)
        }
        
        // 请求保持屏幕常亮
        if (window.plus.device) {
          window.plus.device.setWakelock(true)
        }
        
        console.log('H5PlusBackgroundManager: 后台运行权限已请求')
      } catch (error) {
        console.warn('H5PlusBackgroundManager: 后台运行权限请求失败:', error)
      }
    }
  }

  // 发送保持活跃信号
  sendKeepAliveSignal() {
    if (typeof window.plus !== 'undefined' && window.plus.runtime) {
      try {
        // 发送心跳信号
        window.plus.runtime.getProperty('version', (version) => {
          // 这个调用本身就是一个活跃信号
          console.log('H5PlusBackgroundManager: 心跳信号已发送, 版本:', version)
        })
        
        // 如果有推送服务，发送推送心跳
        if (window.plus.push) {
          window.plus.push.getClientInfo((info) => {
            console.log('H5PlusBackgroundManager: 推送心跳已发送:', info.clientid)
          })
        }
      } catch (error) {
        console.warn('H5PlusBackgroundManager: 心跳信号发送失败:', error)
      }
    }
  }

  // 页面变为可见时的处理
  onPageVisible() {
    console.log('H5PlusBackgroundManager: 页面变为可见')
    
    // 可以在这里添加页面变为可见时的处理逻辑
    // 比如同步计时器状态、更新UI等
    
    // 发送一个活跃信号
    this.sendKeepAliveSignal()
  }

  // 页面变为隐藏时的处理
  onPageHidden() {
    console.log('H5PlusBackgroundManager: 页面变为隐藏')
    
    // 可以在这里添加页面变为隐藏时的处理逻辑
    // 比如保存当前状态、发送后台通知等
    
    // 确保后台运行权限
    this.requestBackgroundPermission()
  }

  // 获取后台运行状态
  getBackgroundStatus() {
    if (!isH5PlusApp()) {
      return { supported: false, message: '非H5+ App环境' }
    }
    
    return {
      supported: true,
      initialized: this.isInitialized,
      hasBackgroundPermission: typeof window.plus !== 'undefined' && window.plus.runtime,
      hasKeepAlive: !!this.keepAliveInterval,
      hasVisibilityHandler: !!this.visibilityChangeHandler
    }
  }

  // 清理资源
  cleanup() {
    if (this.keepAliveInterval) {
      clearInterval(this.keepAliveInterval)
      this.keepAliveInterval = null
    }
    
    if (this.visibilityChangeHandler) {
      document.removeEventListener('visibilitychange', this.visibilityChangeHandler)
      this.visibilityChangeHandler = null
    }
    
    // 释放屏幕常亮
    if (typeof window.plus !== 'undefined' && window.plus.device) {
      try {
        window.plus.device.setWakelock(false)
      } catch (error) {
        console.warn('H5PlusBackgroundManager: 释放屏幕常亮失败:', error)
      }
    }
    
    this.isInitialized = false
    console.log('H5PlusBackgroundManager: 资源已清理')
  }
}

// 创建单例实例
const h5plusBackgroundManager = new H5PlusBackgroundManager()

export default h5plusBackgroundManager

// 导出便捷函数
export const initH5PlusBackground = () => {
  return h5plusBackgroundManager.init()
}

export const getH5PlusBackgroundStatus = () => {
  return h5plusBackgroundManager.getBackgroundStatus()
}

export const cleanupH5PlusBackground = () => {
  return h5plusBackgroundManager.cleanup()
}

